<?php
/**
 * Description of LanceDAO
 *
 * @author Magno
 */
class LanceDAO {

    private $conexao;
    private $leilaoDAO;
    private $clienteDAO;

    public function __construct() {
        $this->conexao = Conexao::getConexao();
        $this->leilaoDAO = new LeilaoDAO();
        $this->clienteDAO = new ClienteDAO();
    }

    public function salvarSimples($lanceID,$leilaoID,$usuarioID){
        try {


            $statment = $this->conexao->prepare("INSERT INTO lance(lanceID,leilaoID,usuarioID)
                    VALUES ($lanceID,$leilaoID,$usuarioID);");

            return $statment->execute();
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

    public function salvar($lance) {

        try {

            if ($lance->getLanceID() != null && $lance->getLanceID() > 0) {
                //não tem edição
                return $lance;
            } else {

                $statment = $this->conexao->prepare("INSERT INTO lance(lanceID,leilaoID,usuarioID)
                    VALUES (:lanceID,:leilaoID,:usuarioID);");
            }

            if ($statment->execute($lance->toBD())) {

                if ($lance->getLanceID() == null || $lance->getLanceID() <= 0)
                    $lance->setLanceID($this->conexao->lastInsertId());
                return $lance;
            }else {
                $erros = $statment->errorInfo();
                throw new Exception("Erro LanceDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

    public function excluir($lanceID) {

        try {

            $statment = $this->conexao->prepare("DELETE FROM lance WHERE lanceID = :lanceID");
            $statment->bindParam(':lanceID', $lanceID);

            if (!$statment->execute()) {
                $erros = $statment->errorInfo();
                throw new Exception("Erro LanceDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

    public function listar($pagina = 0, $leilaoID = -1, $usuarioID = -1, $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina);
            $where = $this->getWhere($leilaoID, $usuarioID);
            $lances = array();
            $statment = $this->conexao->query("SELECT * FROM lance u $where $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $lance = new LanceBean($row['lanceID'], $row['data']);

                if($carregarDependencias){
                    $lance->setLeilao($this->leilaoDAO->buscarPorID($row['leilaoID']));
                    $lance->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }

                $lances[] =  $lance;
            }

            return $lances;
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

    public function listarPorOrdem($pagina = 0, $tamanho = 0, $ordem = "lanceID", $direcao = "DESC", $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina,$tamanho);
            $lances = array();
            $statment = $this->conexao->query("SELECT * FROM lance u ORDER BY u.$ordem $direcao $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $lance = new LanceBean($row['lanceID'], $row['data']);

                if($carregarDependencias){
                    $lance->setLeilao($this->leilaoDAO->buscarPorID($row['leilaoID']));
                    $lance->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }
                
                $lances[] = $lance;
            }

            return $lances;
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

    public function buscarPorID($lanceID, $carregarDependencias = false) {
        try {

            $row = $this->conexao->query("SELECT * FROM lance WHERE lanceID = $lanceID ")->fetch(PDO::FETCH_SERIALIZE);

            if (isset ($row['lanceID']) && $row['lanceID'] > 0) {
                $lance = new LanceBean($row['lanceID'], $row['data']);

                if($carregarDependencias){
                    $lance->setLeilao($this->leilaoDAO->buscarPorID($row['leilaoID']));
                    $lance->setCliente($this->clienteDAO->buscarPorID($row['usuarioID']));
                }
                
                return $lance;
            } else {
                return null;
            }
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

    protected function getWhere($leilaoID = -1,$usuarioID = -1) {

        $where = " WHERE 1 = 1 ";

        if (isset($leilaoID) && $leilaoID > 0) {
            $where = $where . " AND u.leilaoID = $leilaoID ";
        }

        if (isset($usuarioID) && $usuarioID > 0) {
            $where = $where . " AND u.usuarioID = $usuarioID ";
        }

        return $where;
    }

    public function total($leilaoID = -1,$usuarioID = -1) {
        try {

            $where = $this->getWhere($leilaoID, $usuarioID);
            $total = $this->conexao->query("SELECT COUNT(u.lanceID) total FROM lance u $where")->fetch(PDO::FETCH_COLUMN);
            return $total;
        } catch (PDOException $err) {
            throw new Exception("Erro LanceDAO:" . $err->getMessage());
        }
    }

}
?>